/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SLE_ANNOUNCE_IMPL_H
#define SLE_ANNOUNCE_IMPL_H

#include <condition_variable>
#include <mutex>
#include <chrono>
#include "sle_utils_observer_list.h"
#include "i_sle_announce.h"
#include "sle_announce_interface.h"
#include "sle_announce_callback_stub.h"
#include "sle_discover_announce_parcel.h"
#include "sle_host_interface.h"

namespace OHOS {
namespace NearLink {
namespace SleStandard {
class SleAnnounce::SleAnnounceImpl {
public:
    SleAnnounceImpl();
    ~SleAnnounceImpl();
    SleErrorCode CheckOperation();

    class SleAnnounceCallbackStubImpl;
    sptr<SleAnnounceCallbackStubImpl> callbackImpl_ = nullptr; // 该层自己的回调类，注册到下层

    sptr<ISleAnnounce> proxy_ = nullptr;
    sptr<IRemoteObject::DeathRecipient> deathRecipient_ = nullptr;
    SleObserverList<SleAnnounceCallback> callbacks_;

    std::condition_variable conditionVariable_;
    bool ready_ = false;
    std::mutex mtx_;
    std::mutex mutexProxy_;
    SleAnnounceState state_ = SLE_ANNOUNCE_ERROR_STATE;

private:
    void GetProxy();
    void ResetService(const wptr<IRemoteObject> &remote);
};

class SleAnnounce::SleAnnounceImpl::SleAnnounceCallbackStubImpl : public SleAnnounceCallbackStub {
public:
    SleAnnounceCallbackStubImpl(SleAnnounce::SleAnnounceImpl &impl) : impl_(impl) {}
    ~SleAnnounceCallbackStubImpl() = default;

    void OnAnnounceStateChange(uint8_t announceId, int32_t state, bool terminal) override
    {
        impl_.state_ = (SleAnnounceState)state;
        impl_.ready_ = true;
        impl_.conditionVariable_.notify_one();
        impl_.callbacks_.ForEach([announceId, state, terminal](std::shared_ptr<SleAnnounceCallback> callback) {
            callback->OnAnnounceStateChange(announceId, (SleAnnounceState)state, terminal);
        });
    }

private:
    SleAnnounce::SleAnnounceImpl &impl_;
    SLE_DISALLOW_COPY_AND_ASSIGN(SleAnnounceCallbackStubImpl);
};
} // SleStandard
} // NearLink
} // OHOS

#endif // SLE_ANNOUNCE_IMPL_H